package com.beiding.workordersystem.system.beans;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.beiding.workordersystem.common.utils.QueryUtils;
import com.beiding.workordersystem.system.dao.TaskDao;
import com.beiding.workordersystem.system.entity.TaskEntity;
import com.gitee.beiding.timer.Task;
import com.gitee.beiding.timer.TaskRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class TaskRepositoryImpl implements TaskRepository {

    @Autowired
    private TaskDao taskDao;

    @Override
    public void deleteById(String s) {
        taskDao.deleteById(s);
    }

    @Override
    public void save(Task task) {
        task.setId(UUID.randomUUID().toString());
        TaskEntity taskEntity = new TaskEntity();
        taskEntity.setId(task.getId());
        taskEntity.setJson(task.getPayloadJson());
        taskEntity.setType(task.getPayloadType());
        taskEntity.setExecuteTime(task.getExecuteTime());
        taskEntity.setPublishTime(task.getPublishTime());
        taskEntity.setName(task.getName());

        taskDao.insert(taskEntity);

    }

    @Override
    public Set<Task> getRange(long from, long to) {
        LambdaQueryWrapper<TaskEntity> wrapper = QueryUtils.getQuery(TaskEntity.class).ge(TaskEntity::getExecuteTime, from).lt(TaskEntity::getExecuteTime, to);
        List<TaskEntity> taskEntities = taskDao.selectList(wrapper);

        if (taskEntities.size() == 0) {
            return Collections.emptySet();
        }

        Set<Task> tasks = new HashSet<>();
        for (TaskEntity taskEntity : taskEntities) {
            Task task = new Task(taskEntity.getName(), taskEntity.getId(), taskEntity.getType(), taskEntity.getJson(), taskEntity.getExecuteTime());
            tasks.add(task);
        }
        return tasks;
    }
}
